<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>操作系统从0到1 | 惜缘怀古的博客</title><meta name="keywords" content="惜缘怀古，博客"><meta name="author" content="惜缘怀古"><meta name="copyright" content="惜缘怀古"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="一 部署工作环境开发环境：Ubuntu 20.04 LTS 首先是需要安装的东西： 123sudo apt install build-essentialsudo apt-get install libghc-x11-devsudo apt-get install xorg-dev  下载Bochs https:&#x2F;&#x2F;udomain.dl.sourceforge.net&#x2F;project&#x2F;bochs&#x2F;">
<meta property="og:type" content="article">
<meta property="og:title" content="操作系统从0到1">
<meta property="og:url" content="https://xiyuanhuaigu.gitee.io/2023/07/01/%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F%E4%BB%8E0%E5%88%B01/index.html">
<meta property="og:site_name" content="惜缘怀古的博客">
<meta property="og:description" content="一 部署工作环境开发环境：Ubuntu 20.04 LTS 首先是需要安装的东西： 123sudo apt install build-essentialsudo apt-get install libghc-x11-devsudo apt-get install xorg-dev  下载Bochs https:&#x2F;&#x2F;udomain.dl.sourceforge.net&#x2F;project&#x2F;bochs&#x2F;">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://xyhutc.oss-cn-qingdao.aliyuncs.com/giteetuchuang/1687969867170.jpg">
<meta property="article:published_time" content="2023-07-01T13:21:45.000Z">
<meta property="article:modified_time" content="2023-10-15T07:24:31.147Z">
<meta property="article:author" content="惜缘怀古">
<meta property="article:tag" content="惜缘怀古，博客">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://xyhutc.oss-cn-qingdao.aliyuncs.com/giteetuchuang/1687969867170.jpg"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="https://xiyuanhuaigu.gitee.io/2023/07/01/%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F%E4%BB%8E0%E5%88%B01/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isanchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '操作系统从0到1',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-10-15 15:24:31'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if (GLOBAL_CONFIG_SITE.isHome && /iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 5.4.0"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/img/2.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data is-center"><div class="data-item"><a href="/archives/"><div class="headline">文章</div><div class="length-num">66</div></a></div><div class="data-item"><a href="/tags/"><div class="headline">标签</div><div class="length-num">0</div></a></div><div class="data-item"><a href="/categories/"><div class="headline">分类</div><div class="length-num">0</div></a></div></div><hr/></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://xyhutc.oss-cn-qingdao.aliyuncs.com/giteetuchuang/1687969867170.jpg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">惜缘怀古的博客</a></span><div id="menus"><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">操作系统从0到1</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2023-07-01T13:21:45.000Z" title="发表于 2023-07-01 21:21:45">2023-07-01</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-10-15T07:24:31.147Z" title="更新于 2023-10-15 15:24:31">2023-10-15</time></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">3.2k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>11分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="操作系统从0到1"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="一-部署工作环境"><a href="#一-部署工作环境" class="headerlink" title="一 部署工作环境"></a>一 部署工作环境</h1><p>开发环境：Ubuntu 20.04 LTS</p>
<p>首先是需要安装的东西：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">sudo apt install build-essential</span><br><span class="line">sudo apt-get install libghc-x11-dev</span><br><span class="line">sudo apt-get install xorg-dev</span><br></pre></td></tr></table></figure>

<p>下载Bochs <a target="_blank" rel="noopener" href="https://udomain.dl.sourceforge.net/project/bochs/bochs/2.6.8/bochs-2.6.8.tar.gz">https://udomain.dl.sourceforge.net/project/bochs/bochs/2.6.8/bochs-2.6.8.tar.gz</a></p>
<p>下载完毕之后将其移动至虚拟机中想要的位置，然后解压，命令：tar -zxvf bochs-2.6.8.tar.gz</p>
<p>为即将要安装的bochs创建一个空目录</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">mkdir bochs</span><br></pre></td></tr></table></figure>

<p>进入解压后的bochs-2.6.8文件夹 cd bochs-2.6.8</p>
<p>配置bochs的config文件（–prefix这后面填的是你想要安装bochs的目录），编译，安装</p>
<p>./configure –prefix=/home/ubuntu/Desktop/bochs –enable-debugger –enable-disasm –enable-iodebug –enable-x86-debugger –with-x –with-x11 LDFLAGS=’-pthread’</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">make</span><br><span class="line"></span><br><span class="line">make install</span><br></pre></td></tr></table></figure>

<p>进入安装好bochs的目录 cd .. cd bochs创建bochsrc.disk 命令: touch bochsrc.disk，在其中写下配置信息（修改romimage:、romimage:、 keyboard:后面路径信息的前部分为自己的bochs安装路径）</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">megs : 32</span><br><span class="line"></span><br><span class="line">romimage: file=/home/ubuntu/Desktop/bochs/share/bochs/BIOS-bochs-latest</span><br><span class="line">vgaromimage: file=/home/ubuntu/Desktop/bochs/share/bochs/VGABIOS-lgpl-latest</span><br><span class="line"></span><br><span class="line">boot: disk</span><br><span class="line"></span><br><span class="line">log: bochs.out</span><br><span class="line"></span><br><span class="line">mouse:enabled=0</span><br><span class="line">keyboard:keymap=/home/ubuntu/Desktop/bochs/share/bochs/keymaps/x11-pc-us.map</span><br><span class="line"></span><br><span class="line">ata0:enabled=1,ioaddr1=0x1f0,ioaddr2=0x3f0,irq=14</span><br><span class="line">ata0-master: type=disk, path=&quot;hd60M.img&quot;, mode=flat,cylinders=121,heads=16,spt=63</span><br><span class="line"></span><br><span class="line">#gdbstub:enabled=1,port=1234,text_base=0,data_base=0,bss_base=0</span><br></pre></td></tr></table></figure>

<p>创建启动磁盘</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">bin/bximage</span><br></pre></td></tr></table></figure>

<p>然后在输入框依次输入以下，输入一个，按一次回车</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">1</span><br><span class="line">hd</span><br><span class="line">flat </span><br><span class="line">60</span><br><span class="line">hd60M.img</span><br></pre></td></tr></table></figure>

<p>测试代码,以下内容用作测试：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">cd ..</span><br><span class="line">touch mbr.s</span><br></pre></td></tr></table></figure>

<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line">SECTION MBR vstart=0x7c00</span><br><span class="line">	mov ax,0x0000	;设置栈指应该是程序一开始就应该做的事情,这个值是参照1m内存空间布局图选择的，以后会刻意避开</span><br><span class="line">	mov ss,ax</span><br><span class="line">	mov ax,0x7c00</span><br><span class="line">	mov sp,ax	</span><br><span class="line"> </span><br><span class="line">	mov ax,0x0600</span><br><span class="line">	mov bx,0x0700	;BH是设置缺省属性，属性是指背景色，前景色，是否闪烁等，例如07H表示黑底白字，70H表示灰底黑字等等。</span><br><span class="line">	mov cx,0x0000</span><br><span class="line">	mov dx,0x184f	;这个看书p61，同时看其中关于页的知识</span><br><span class="line">	int 0x10</span><br><span class="line">	</span><br><span class="line">	mov ax,0x0300	</span><br><span class="line">	mov bx,0x0000	</span><br><span class="line">	int 0x10</span><br><span class="line">	</span><br><span class="line">	mov ax,0x0000</span><br><span class="line">	mov es,ax</span><br><span class="line">	mov ax,message</span><br><span class="line">	mov bp,ax</span><br><span class="line">	mov ax,0x1301</span><br><span class="line">	mov bx,0x0007	;设置字体属性，02是黑底绿字，07是黑底白字</span><br><span class="line">	mov cx,0x000c</span><br><span class="line">	int 0x10</span><br><span class="line">	</span><br><span class="line">	jmp $</span><br><span class="line">	message db &quot;Hello World!&quot;</span><br><span class="line">	times 510-($-$$) db 0</span><br><span class="line">	db 0x55,0xaa</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>安装编译器nasm 命令: </p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">sudo apt install nasm</span><br></pre></td></tr></table></figure>

<p>编译</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">nasm -o test mbr.s</span><br></pre></td></tr></table></figure>

<p>写入虚拟机启动磁盘 </p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">dd if=/home/ubuntu/Desktop/test of=/home/ubuntu/Desktop/bochs/hd60M.img bs=512 count=1 conv=notrunc</span><br></pre></td></tr></table></figure>

<p>启动虚拟机查看效果（在bochs目录下）</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">cd bochs</span><br><span class="line"></span><br><span class="line">bin/bochs -f bochsrc.disk</span><br></pre></td></tr></table></figure>

<p>启动之后，输入c即可看见Hello world!</p>
<h1 id="二-编写-MBR-主引导记录，让我们开始掌权"><a href="#二-编写-MBR-主引导记录，让我们开始掌权" class="headerlink" title="二 编写 MBR 主引导记录，让我们开始掌权"></a>二 编写 MBR 主引导记录，让我们开始掌权</h1><h2 id="2-1-计算机的启动过程"><a href="#2-1-计算机的启动过程" class="headerlink" title="2.1 计算机的启动过程"></a>2.1 计算机的启动过程</h2><p>任何程序执行必须先载入内存，所谓的载入内存，大概上分为两个部分。</p>
<p>（1）程序被加载器（软件或硬件）加载到内存某个区域。</p>
<p>（2）CPU 的 cs：ip 寄存器被指向这个程序的起始地址</p>
<p>从按下主机上的 power 键后，第一个运行的软件是 BIOS。</p>
<h2 id="2-2-软件接力第一棒，BIOS"><a href="#2-2-软件接力第一棒，BIOS" class="headerlink" title="2.2 软件接力第一棒，BIOS"></a>2.2 软件接力第一棒，BIOS</h2><p>BIOS 全称叫 Base Input &amp; Output System，即基本输入输出系统。</p>
<h3 id="2-2-1-实模式下的-1MB-内存布局"><a href="#2-2-1-实模式下的-1MB-内存布局" class="headerlink" title="2.2.1 实模式下的 1MB 内存布局"></a>2.2.1 实模式下的 1MB 内存布局</h3><p>这里我们举例Intel 8086在实模式下的内存布局</p>
<p><img src="https://xyhutc.oss-cn-qingdao.aliyuncs.com/giteetuchuang/20230703001736.png"></p>
<p>先从低地址看，地址 0～0x9FFFF 处是 DRAM（Dynamic Random Access Memory），即动态随机访问 内存，我们所装的物理内存就是 DRAM。</p>
<p>看顶部的 0xF0000～0xFFFFF，这 64KB 的内 存是 ROM。这里面存的就是 BIOS 的代码。BIOS 的主要工作是检测、初始化硬件，怎么初始化的？硬件自己提 供了一些初始化的功能调用，BIOS 直接调用就好了。BIOS 还做了一件伟大的事情，建立了中断向量表，这样 就可以通过“int 中断号”来实现相关的硬件调用，当然 BIOS 建立的这些功能就是对硬件的 IO 操作，也就是输 入输出，但由于就 64KB 大小的空间，不可能把所有硬件的 IO 操作实现得面面俱到，而且也没必要实现那么多， 毕竟是在实模式之下，对硬件支持得再丰富也白搭，精彩的世界是在进入保护模式以后才开始，所以挑一些重要 的、保证计算机能运行的那些硬件的基本 IO 操作，就行了。这就是 BIOS 称为基本输入输出系统的原因。</p>
<p>在CPU眼里，插在主板上的物理内存并不是它眼里的“全部的内存”，归根结底的原因是这样的：在计算机中，并不是只有咱们插在主板上的内存条需要通过地址总线访问， 还有一些外设同样是需要通过地址总线来访问的，这类设备还很多呢。若把全部的地址总线都指向物理内 存，那其他设备该如何访问呢？由于这个原因，只好在地址总线上提前预留出来一些地址空间给这些外设 用，这片连续的地址给显存，这片连续的地址给硬盘控制器等。留够了以后，地址总线上其余的可用地址 再指向 DRAM，也就是指插在主板上的内存条、我们眼中的物理内存。</p>
<h3 id="2-2-2-BIOS-是如何苏醒的"><a href="#2-2-2-BIOS-是如何苏醒的" class="headerlink" title="2.2.2 BIOS 是如何苏醒的"></a>2.2.2 BIOS 是如何苏醒的</h3><p>BIOS 本身是个程序，程序要执行，就要有个入口地址才行，此入口地址便是 0xFFFF0。在开机的一瞬间，也就是接电的一瞬间，CPU 的 cs：ip 寄存器被强制初始化为 0xF000：0xFFF0。由于 开机的时候处于实模式，再重复一遍加深印象，在实模式下的段基址要乘以16，也就是左移4位，于是0xF000： 0xFFF0 的等效地址将是 0xFFFF0。上面说过了，此地址便是 BIOS 的入口地址。但是此处并不是真正的代码，因为由于实模式下的寄存器宽度是 16 位，0xFFFF0+16 已经超过了其最大值 0xFFFFF。溢出的部分就会回卷到 0，又会重新开始，即 0xFFFF0+16 等于 0，0xFFFF0+17 等于 1。所以此处的代码为跳转代码。真正的代码储存在跳转代码的所跳转的位置，接下来 BIOS 便马不停蹄地检测内存、显卡等外设信息，当检测通过，并初始化好硬件后，开始在内 存中 0x000～0x3FF 处建立数据结构，中断向量表 IVT 并填写中断例程。</p>
<h3 id="2-2-3-为什么是-0x7c00"><a href="#2-2-3-为什么是-0x7c00" class="headerlink" title="2.2.3 为什么是 0x7c00"></a>2.2.3 为什么是 0x7c00</h3><p>计算机执行到这份上，BIOS 也即将完成自己的历史使命了，BIOS 最后一项工作校验启动盘中位于 0 盘 0 道 1 扇区的内容。如果此扇区末尾的两个字节分别是魔数 0x55 和 0xaa，BIOS 便认为此扇区中确实存在可执 行的程序（在此先剧透一下，此程序便是久闻大名的主引导记录 MBR），便加载到物理地址 0x7c00，随 后跳转到此地址，继续执行。至于为什么是 0x7c00，8086CPU 要求物理地址 0x0～0x3FF 存放中断向量表，所以此处不能动了，再选新的地方看看。 按 DOS 1.0 要求的最小内存 32KB 来说，MBR 希望给人家尽可能多的预留空间，这样也是保全自己 的作法，免得过早被覆盖。所以 MBR 只能放在 32KB 的末尾。 MBR 本身也是程序，是程序就要用到栈，栈也是在内存中的，MBR 虽然本身只有 512 字节，但还要为其 所用的栈分配点空间，所以其实际所用的内存空间要大于 512 字节，估计 1KB 内存够用了。 结合以上三点，选择32KB中的最后1KB最为合适，那此地址是多少呢？32KB换算为十六进制为0x8000， 减去 1KB(0x400)的话，等于 0x7c00。这就是倍受质疑的 0x7c00 的由来，这下清楚了。 可见，加载 MBR 的位置取决于操作系统本身所占内存大小和内存布局。</p>
<h2 id="2-3-让-MBR-先飞一会儿"><a href="#2-3-让-MBR-先飞一会儿" class="headerlink" title="2.3 让 MBR 先飞一会儿"></a>2.3 让 MBR 先飞一会儿</h2><p>MBR 的大小必须是 512 字节，这是为了保证 0x55 和 0xaa 这两个 魔数恰好出现在该扇区的最后两个字节处，即第 510 字节处和第 511 字节处，这是按起始偏移为 0 算起的。 由于我们的 bochs 模拟的是 x86 平台，所以是小端字节序，故其最后两个字节内容是 0xaa55</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br></pre></td><td class="code"><pre><span class="line">                                ;主引导程序 </span><br><span class="line">                                ;------------------------------------------------------------</span><br><span class="line">SECTION MBR vstart=0x7c00         </span><br><span class="line">    mov ax,cs                   ;此时cs寄存器为0，自然可以用来将ax寄存器置0</span><br><span class="line">    mov ds,ax</span><br><span class="line">    mov es,ax</span><br><span class="line">    mov ss,ax</span><br><span class="line">    mov fs,ax</span><br><span class="line">    mov sp,0x7c00</span><br><span class="line"></span><br><span class="line">                                ; 清屏 利用0x06号功能，上卷全部行，则可清屏。</span><br><span class="line">                                ; -----------------------------------------------------------</span><br><span class="line">                                ;INT 0x10   功能号:0x06	   功能描述:上卷窗口</span><br><span class="line">                                ;------------------------------------------------------</span><br><span class="line">                                ;输入：</span><br><span class="line">                                ;AH 功能号= 0x06</span><br><span class="line">                                ;AL = 上卷的行数(如果为0,表示全部)</span><br><span class="line">                                ;BH = 上卷行属性</span><br><span class="line">                                ;(CL,CH) = 窗口左上角的(X,Y)位置</span><br><span class="line">                                ;(DL,DH) = 窗口右下角的(X,Y)位置</span><br><span class="line">                                ;无返回值：</span><br><span class="line">    mov ax, 0x600               ;ah中输入功能号</span><br><span class="line">    mov bx, 0x700               ;设置上卷行属性，0x70表示用黑底白字的属性填充空白行</span><br><span class="line">    mov cx, 0                   ;左上角: (0, 0)</span><br><span class="line">    mov dx, 0x184f	            ;右下角: (80,25),</span><br><span class="line">			                    ;VGA文本模式中,一行只能容纳80个字符,共25行。</span><br><span class="line">			                    ;下标从0开始,所以0x18=24,0x4f=79</span><br><span class="line">    int 0x10                    ;int 0x10</span><br><span class="line"></span><br><span class="line">                                ;;;;;;;;;    下面这三行代码是获取光标位置    ;;;;;;;;;</span><br><span class="line">    mov ah, 3		            ;输入: 3号子功能是获取光标位置,需要存入ah寄存器</span><br><span class="line">    mov bh, 0		            ;bh寄存器存储的是待获取光标的页号</span><br><span class="line"></span><br><span class="line">    int 0x10		            ;输出: ch=光标开始行,cl=光标结束行</span><br><span class="line">		    	                ;dh=光标所在行号,dl=光标所在列号</span><br><span class="line"></span><br><span class="line">                                ;;;;;;;;;    获取光标位置结束    ;;;;;;;;;;;;;;;;</span><br><span class="line"></span><br><span class="line">                                ;;;;;;;;;     打印字符串    ;;;;;;;;;;;</span><br><span class="line">                                ;还是用10h中断,不过这次是调用13号子功能打印字符串</span><br><span class="line">    mov ax, message </span><br><span class="line">    mov bp, ax		            ; es:bp 为串首地址, es此时同cs一致，</span><br><span class="line">			                    ; 开头时已经为sreg初始化</span><br><span class="line"></span><br><span class="line">                                ; 光标位置要用到dx寄存器中内容,cx中的光标位置可忽略</span><br><span class="line">    mov cx, 5		            ; cx 为串长度,不包括结束符0的字符个数</span><br><span class="line">    mov ax, 0x1301	            ; 子功能号13是显示字符及属性,要存入ah寄存器,</span><br><span class="line">			                    ; al设置写字符方式 ah=01: 显示字符串,光标跟随移动</span><br><span class="line">    mov bx, 0x2		            ; bh存储要显示的页号,此处是第0页,</span><br><span class="line">			                    ; bl中是字符属性, 属性黑底绿字(bl = 02h,07是黑底白字)</span><br><span class="line">    int 0x10		            ; 执行BIOS 0x10 号中断</span><br><span class="line">                                ;;;;;;;;;      打字字符串结束	 ;;;;;;;;;;;;;;;</span><br><span class="line"></span><br><span class="line">    jmp $		                ; 使程序悬停在此</span><br><span class="line"></span><br><span class="line">    message db &quot;1 MBR&quot;</span><br><span class="line">    times 510-($-$$) db 0</span><br><span class="line">    db 0x55,0xaa</span><br><span class="line"></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>注：使用dd命令时需要重新创建硬盘</p>
<p>创建启动磁盘</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">bin/bximage</span><br></pre></td></tr></table></figure>

<p>然后在输入框依次输入以下，输入一个，按一次回车</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">1</span><br><span class="line">hd</span><br><span class="line">flat </span><br><span class="line">60</span><br><span class="line">hd60M.img</span><br></pre></td></tr></table></figure>



<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">nasm -o mbr mbr.s</span><br></pre></td></tr></table></figure>

<p>然后用dd命令写入bochs的虚拟硬盘，命令:</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">dd if=/home/ubuntu/Desktop/test of=/home/ubuntu/Desktop/bochs/hd60M.img bs=512 count=1 conv=notrunc</span><br></pre></td></tr></table></figure>

<p>启动，之后默认为6输入c</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">bin/bochs –f bochsrc.disk</span><br></pre></td></tr></table></figure>

<p>可以看到有结果出现</p>
<h1 id="三-完善MBR"><a href="#三-完善MBR" class="headerlink" title="三 完善MBR"></a>三 完善MBR</h1><h2 id="3-1-地址，section-vstart浅尝辄止"><a href="#3-1-地址，section-vstart浅尝辄止" class="headerlink" title="3.1 地址，section,vstart浅尝辄止"></a>3.1 地址，section,vstart浅尝辄止</h2><h3 id="3-1-1-什么是地址"><a href="#3-1-1-什么是地址" class="headerlink" title="3.1.1 什么是地址"></a>3.1.1 什么是地址</h3><p>地址只是数字，描述各种符号在源程序中的位置，它是源代码文件中各符号偏移文件开头的距离。由 于指令和变量所占内存大小不同，故它们相对于文件开头的偏移量参差不齐。源文件就像旅店一样，里面 的符号（指令、变量等）就像旅店里的房间，有单人间、双人间，虽然大小不同，但它们也需要被旅店管 理员编号，也就是每个房间都有房间号，这样房客通过房间号便能找到自己的住所。</p>
<h3 id="3-1-2-什么是section"><a href="#3-1-2-什么是section" class="headerlink" title="3.1.2 什么是section"></a>3.1.2 什么是section</h3><p>简单点来说就是方便开发人员理清程序用的，关键字 section 并没有对程序中的地址产生任何影响，即在默 认情况下，有没有 section 都一个样，section 中数据的地址依然是相对于整个文件的顺延，仅仅是在逻辑 上让开发人员梳理程序之用</p>
<h3 id="3-1-3-什么是vstart"><a href="#3-1-3-什么是vstart" class="headerlink" title="3.1.3 什么是vstart"></a>3.1.3 什么是vstart</h3><p>vstart 的作用是为 section 内的数据指定 个虚拟的起始地址，也就是根据此地址，在文件中是找不到 相关数据的，是虚拟的，假的，文件中的所有符号都不在这个地址上。vstart 只是告诉编译器以新的数字作为后面数据的地址的起始值，它本身没改变数据本 身在文件中的地址（相对于文件开头的偏移〉</p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">惜缘怀古</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://xiyuanhuaigu.gitee.io/2023/07/01/%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F%E4%BB%8E0%E5%88%B01/">https://xiyuanhuaigu.gitee.io/2023/07/01/%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F%E4%BB%8E0%E5%88%B01/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://xiyuanhuaigu.gitee.io" target="_blank">惜缘怀古的博客</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"></div><div class="post_share"><div class="social-share" data-image="https://xyhutc.oss-cn-qingdao.aliyuncs.com/giteetuchuang/1687969867170.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2023/08/15/r0capture%E9%85%8D%E7%BD%AE%E5%8F%8A%E4%BD%BF%E7%94%A8/"><img class="prev-cover" src="https://xyhutc.oss-cn-qingdao.aliyuncs.com/giteetuchuang/e949e0eafeff40990e43c84788d0da792aa57820_raw.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">r0capture配置及使用</div></div></a></div><div class="next-post pull-right"><a href="/2023/04/24/buuctfRE/"><img class="next-cover" src="https://xyhutc.oss-cn-qingdao.aliyuncs.com/giteetuchuang/1681534560034.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">buuctfRE</div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/img/2.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">惜缘怀古</div><div class="author-info__description">唯有那份炫目，未曾忘却</div></div><div class="card-info-data is-center"><div class="card-info-data-item"><a href="/archives/"><div class="headline">文章</div><div class="length-num">66</div></a></div><div class="card-info-data-item"><a href="/tags/"><div class="headline">标签</div><div class="length-num">0</div></a></div><div class="card-info-data-item"><a href="/categories/"><div class="headline">分类</div><div class="length-num">0</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/xxxxxx"><i class="fab fa-github"></i><span>Follow Me</span></a></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content">This is my Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%B8%80-%E9%83%A8%E7%BD%B2%E5%B7%A5%E4%BD%9C%E7%8E%AF%E5%A2%83"><span class="toc-number">1.</span> <span class="toc-text">一 部署工作环境</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%BA%8C-%E7%BC%96%E5%86%99-MBR-%E4%B8%BB%E5%BC%95%E5%AF%BC%E8%AE%B0%E5%BD%95%EF%BC%8C%E8%AE%A9%E6%88%91%E4%BB%AC%E5%BC%80%E5%A7%8B%E6%8E%8C%E6%9D%83"><span class="toc-number">2.</span> <span class="toc-text">二 编写 MBR 主引导记录，让我们开始掌权</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#2-1-%E8%AE%A1%E7%AE%97%E6%9C%BA%E7%9A%84%E5%90%AF%E5%8A%A8%E8%BF%87%E7%A8%8B"><span class="toc-number">2.1.</span> <span class="toc-text">2.1 计算机的启动过程</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-2-%E8%BD%AF%E4%BB%B6%E6%8E%A5%E5%8A%9B%E7%AC%AC%E4%B8%80%E6%A3%92%EF%BC%8CBIOS"><span class="toc-number">2.2.</span> <span class="toc-text">2.2 软件接力第一棒，BIOS</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#2-2-1-%E5%AE%9E%E6%A8%A1%E5%BC%8F%E4%B8%8B%E7%9A%84-1MB-%E5%86%85%E5%AD%98%E5%B8%83%E5%B1%80"><span class="toc-number">2.2.1.</span> <span class="toc-text">2.2.1 实模式下的 1MB 内存布局</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-2-2-BIOS-%E6%98%AF%E5%A6%82%E4%BD%95%E8%8B%8F%E9%86%92%E7%9A%84"><span class="toc-number">2.2.2.</span> <span class="toc-text">2.2.2 BIOS 是如何苏醒的</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-2-3-%E4%B8%BA%E4%BB%80%E4%B9%88%E6%98%AF-0x7c00"><span class="toc-number">2.2.3.</span> <span class="toc-text">2.2.3 为什么是 0x7c00</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-3-%E8%AE%A9-MBR-%E5%85%88%E9%A3%9E%E4%B8%80%E4%BC%9A%E5%84%BF"><span class="toc-number">2.3.</span> <span class="toc-text">2.3 让 MBR 先飞一会儿</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%B8%89-%E5%AE%8C%E5%96%84MBR"><span class="toc-number">3.</span> <span class="toc-text">三 完善MBR</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#3-1-%E5%9C%B0%E5%9D%80%EF%BC%8Csection-vstart%E6%B5%85%E5%B0%9D%E8%BE%84%E6%AD%A2"><span class="toc-number">3.1.</span> <span class="toc-text">3.1 地址，section,vstart浅尝辄止</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#3-1-1-%E4%BB%80%E4%B9%88%E6%98%AF%E5%9C%B0%E5%9D%80"><span class="toc-number">3.1.1.</span> <span class="toc-text">3.1.1 什么是地址</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-1-2-%E4%BB%80%E4%B9%88%E6%98%AFsection"><span class="toc-number">3.1.2.</span> <span class="toc-text">3.1.2 什么是section</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-1-3-%E4%BB%80%E4%B9%88%E6%98%AFvstart"><span class="toc-number">3.1.3.</span> <span class="toc-text">3.1.3 什么是vstart</span></a></li></ol></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2023/11/06/2023%E8%93%9D%E5%B8%BD%E6%9D%AF%E5%86%B3%E8%B5%9BWP/" title="2023蓝帽杯决赛WP"><img src="https://xyhutc.oss-cn-qingdao.aliyuncs.com/giteetuchuang/20231106163334.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="2023蓝帽杯决赛WP"/></a><div class="content"><a class="title" href="/2023/11/06/2023%E8%93%9D%E5%B8%BD%E6%9D%AF%E5%86%B3%E8%B5%9BWP/" title="2023蓝帽杯决赛WP">2023蓝帽杯决赛WP</a><time datetime="2023-11-06T08:31:51.000Z" title="发表于 2023-11-06 16:31:51">2023-11-06</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/10/20/%E6%94%BB%E9%98%B2%E4%B8%96%E7%95%8CRE/" title="攻防世界RE"><img src="https://xyhutc.oss-cn-qingdao.aliyuncs.com/giteetuchuang/c78ed35b1e3999643d52a652257558af0a15b4c9_raw.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="攻防世界RE"/></a><div class="content"><a class="title" href="/2023/10/20/%E6%94%BB%E9%98%B2%E4%B8%96%E7%95%8CRE/" title="攻防世界RE">攻防世界RE</a><time datetime="2023-10-20T12:38:32.000Z" title="发表于 2023-10-20 20:38:32">2023-10-20</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/09/22/%E5%AE%89%E5%8D%93%E5%B8%B8%E7%94%A8%E7%9B%AE%E5%BD%95/" title="安卓常用目录"><img src="https://xyhutc.oss-cn-qingdao.aliyuncs.com/giteetuchuang/mmexport1694863328916.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="安卓常用目录"/></a><div class="content"><a class="title" href="/2023/09/22/%E5%AE%89%E5%8D%93%E5%B8%B8%E7%94%A8%E7%9B%AE%E5%BD%95/" title="安卓常用目录">安卓常用目录</a><time datetime="2023-09-22T01:27:02.000Z" title="发表于 2023-09-22 09:27:02">2023-09-22</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/09/22/010Editor%E7%A0%B4%E8%A7%A3/" title="010Editor破解"><img src="https://xyhutc.oss-cn-qingdao.aliyuncs.com/giteetuchuang/1694867487605.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="010Editor破解"/></a><div class="content"><a class="title" href="/2023/09/22/010Editor%E7%A0%B4%E8%A7%A3/" title="010Editor破解">010Editor破解</a><time datetime="2023-09-22T00:33:10.000Z" title="发表于 2023-09-22 08:33:10">2023-09-22</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/08/24/%E6%9F%90APP%E7%9A%84%E9%80%86%E5%90%91%E5%88%86%E6%9E%90/" title="某APP的逆向分析"><img src="https://xyhutc.oss-cn-qingdao.aliyuncs.com/giteetuchuang/a4c8982faff8839d06cc010c864e02e8092efb23_raw.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="某APP的逆向分析"/></a><div class="content"><a class="title" href="/2023/08/24/%E6%9F%90APP%E7%9A%84%E9%80%86%E5%90%91%E5%88%86%E6%9E%90/" title="某APP的逆向分析">某APP的逆向分析</a><time datetime="2023-08-24T14:02:11.000Z" title="发表于 2023-08-24 22:02:11">2023-08-24</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2024 By 惜缘怀古</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.js"></script><div class="js-pjax"></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>